//
//  DatabaseTool.m
//  Jyxt
//
//  Created by 刘日 on 17/5/25.
//  Copyright © 2017年 DaLian Rental Housing Management. All rights reserved.
//

#import "DatabaseTool.h"

static NSString *DB_PATH = @"/Documents/Jyxt.db";

static FMDatabase *db = nil;

#define KEY_VALUE_TABLE_SQL @"CREATE TABLE IF NOT EXISTS KeyValue ( id integer PRIMARY KEY AUTOINCREMENT NOT NULL,  key1 varchar(512) NOT NULL,  value text NOT NULL )"
#define KEY_VALUE_DELETE_WITH_KEY @"DELETE FROM KeyValue WHERE key1 = ?"
#define KEY_VALUE_INSERT_WITH_KEY @"INSERT INTO KeyValue (key1, value) VALUES (? , ?)"
#define KEY_VALUE_SELECT_WITH_KEY @"SELECT value FROM KeyValue WHERE key1 = ?"


@implementation DatabaseTool

+ (FMDatabase *)getCommonDataBase{
    db = [FMDatabase databaseWithPath: [NSString stringWithFormat: @"%@%@" , NSHomeDirectory() , DB_PATH]];
    [db open];
    return db; 
}

+ (void)closeCommonDataBase{
    [db close];
    db = nil;
}

+ (void)initBaseTable{
    [self getCommonDataBase];
    [db executeUpdate: KEY_VALUE_TABLE_SQL];
    [self closeCommonDataBase];
}

+ (void)putWithKey:(NSString *)key value:(NSString *)value{
    [self getCommonDataBase];
    [db executeUpdate: KEY_VALUE_DELETE_WITH_KEY withArgumentsInArray: @[key]];
    [db executeUpdate: KEY_VALUE_INSERT_WITH_KEY withArgumentsInArray: @[key , value]];
    [self closeCommonDataBase];
}

+ (NSString *)getWithKey:(NSString *)key{
    
    [self getCommonDataBase];
    FMResultSet *res = [db executeQuery: KEY_VALUE_SELECT_WITH_KEY withArgumentsInArray: @[key]];
    NSString *value = nil;
    if ([res next]){
        value = [res stringForColumnIndex: 0];
    }
    [self closeCommonDataBase];
    return value;
}

+ (void)removeWithKey: (NSString *)key{
    [self getCommonDataBase];
    [db executeUpdate: KEY_VALUE_DELETE_WITH_KEY withArgumentsInArray: @[key]];
    [self closeCommonDataBase];
}

@end
